<template>
  <div class="app-container training_detail_root">
    <div class="training_detail_root_top">
      <div class="training_detail_root_top_title">基本信息</div>
<!--      <div class="situation_button">-->
<!--        <el-button-->
<!--          size="mini"-->
<!--          type="primary"-->
<!--          @click="toStudentSituation(form.id)"-->
<!--          style="background: #4F46E5;border: none"-->
<!--        >-->
<!--          <div style="display: flex;align-items: center">-->
<!--            <img src="./studentSituation.png" style="width:16px;height:16px;margin-right: 5px;" alt="" >-->
<!--            学员参与情况-->
<!--          </div>-->
<!--        </el-button>-->
<!--        <el-button-->
<!--          size="mini"-->
<!--          type="primary"-->
<!--          @click="toCourseSituation"-->
<!--          style="background: #9333EA;border: none"-->
<!--        >-->
<!--          <div style="display: flex;align-items: center">-->
<!--            <img src="./courseSituation.png" style="width:16px;height:16px;margin-right: 5px;" alt="" >-->
<!--            课程完成情况-->
<!--          </div>-->
<!--        </el-button>-->
<!--      </div>-->
      <div class="training_detail_root_top_row">
        <div class="training_detail_root_top_row_li">
          <div class="li_title">培训名称</div>
          <div class="li_title_content">{{form.trainingTitle}}</div>
        </div>
        <div class="training_detail_root_top_row_li">
          <div class="li_title">培训地点</div>
          <div class="li_title_content">{{ form.trainingAddress }}</div>
        </div>
      </div>
      <div class="training_detail_root_top_row">
        <div class="training_detail_root_top_row_li">
          <div class="li_title">培训类型</div>
          <div class="li_title_content">
            <dict-tag :options="dict.type.px_type" :value="form.trainingType"/>
          </div>
        </div>
        <div class="training_detail_root_top_row_li">
          <div class="li_title">培训状态</div>
          <div class="li_title_content" ><span class="button-status" :class="form.state==='未开始'?'status4':form.state==='进行中'?'status3':form.state==='已结束'?'status2':''">{{form.state}}</span></div>
        </div>
      </div>
      <div class="training_detail_root_top_row">
        <div class="training_detail_root_top_row_li">
          <div class="li_title">培训时间</div>
          <div class="li_title_content">{{ form.startTime }} ～ {{ form.endTime }}</div>
        </div>
        <div class="training_detail_root_top_row_li">
          <div class="li_title">培训学分</div>
          <div class="li_title_content">{{ form.trainingScore }}学分</div>
        </div>
      </div>
      <div class="training_detail_root_top_row">
        <div class="training_detail_root_top_row_li">
          <div class="li_title">学分发放</div>
          <div class="li_title_content">
            <dict-tag :options="dict.type.px_score_type" :value="form.trainingScoreType"/>
          </div>
        </div>
        <div class="training_detail_root_top_row_li">
        </div>
      </div>
      <div class="training_detail_root_top_row" style="margin-top: 28px;">
        <div class="training_detail_root_top_row_li">
          <div class="li_title">培训描述</div>
          <div class="li_title_content" style="max-height: 80px;overflow-y: auto">{{ form.trainingNotes }}</div>
        </div>
      </div>
    </div>
    <div class="training_detail_root_bottom">
      <el-tabs v-model="activeName" >
        <el-tab-pane label="学员管理" name="first">
          <div class="bottom_content">
            <div class="bottom_content_title">
              <div class="bottom_content_title_left">培训学员</div>
              <div class="bottom_content_title_right">
                <el-button
                  type="primary"
                  icon="el-icon-notebook-2"
                  size="mini"
                  @click="openImportStudent"
                  v-hasPermi="['classai:training:add']"
                  style="padding: 6px 16px;box-sizing: border-box"
                >导入学员</el-button>
                <el-button
                  type="success"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAddStudent"
                  v-hasPermi="['classai:training:add']"
                  style="padding: 6px 16px;box-sizing: border-box"
                >新增学员</el-button>
              </div>
            </div>
            <el-table v-loading="loading" :data="trainingStudentList"  class="teacher_list">
              <el-table-column label="师训号" align="center" prop="teacherNumber" />
              <el-table-column label="学校" align="center" prop="teacherUnit" />
              <el-table-column label="姓名" align="center" prop="teacherName" />
              <el-table-column label="工作职务" align="center" prop="teacherPosition">
                <template slot-scope="scope">
                  <span>{{scope.row.teacherPosition ? scope.row.teacherPosition : '--'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="手机号" align="center" prop="teacherPhone" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleEdit(scope.row)"
                    v-hasPermi="['classai:training:edit']"
                  >
                    <img src="@/assets/images/teacher_edit.png" style="width:16px;height:16px;" alt="">
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDeleteStudent(scope.row)"
                    v-hasPermi="['classai:training:remove']"
                  >
                    <img src="@/assets/images/teacher_del.png" style="width:14px;height:16px;" alt="">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getStudentList"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="课程管理" name="second">
          <div class="bottom_content">
            <div class="bottom_content_title">
              <div class="bottom_content_title_left">培训课程列表</div>
              <div class="bottom_content_title_right">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['classai:training:add']"
                  style="padding: 6px 16px;box-sizing: border-box"
                >新增课程</el-button>
              </div>
            </div>
            <el-table v-loading="loading" :data="trainingCourseList"  class="teacher_list">
              <el-table-column label="培训模块" align="center" prop="moduleTitle">
                <template slot-scope="scope">
                  <span>{{scope.row.moduleTitle ? scope.row.moduleTitle : '--'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="培训主题" align="center" prop="trainingTheme" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{scope.row.trainingTheme ? scope.row.trainingTheme : '--'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="培训形式" align="center" prop="trainingFormat">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.training_format" :value="scope.row.trainingFormat"/>
                </template>
              </el-table-column>
              <el-table-column label="培训专家" align="center" prop="trainingExpert">
                <template slot-scope="scope">
                  <span>{{scope.row.trainingExpert ? scope.row.trainingExpert : '--'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="培训学时" align="center" prop="classHour" />
              <el-table-column label="培训时间" align="center" prop="startTime">
                <template slot-scope="scope">
                  <span>{{scope.row.startTime}} {{scope.row.endTime}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['classai:training:edit']"
                  >
                    <img src="@/assets/images/teacher_edit.png" style="width:16px;height:16px;" alt="">
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['classai:training:remove']"
                  >
                    <img src="@/assets/images/teacher_del.png" style="width:14px;height:16px;" alt="">
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleOpenCode(scope.row)"
                  >
                    <img src="./qrCode.png" style="width:14px;height:16px;" alt="">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="courseTotal>0"
              :total="courseTotal"
              :page.sync="courseQueryParams.pageNum"
              :limit.sync="courseQueryParams.pageSize"
              @pagination="getCourseList"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 添加或修改学员 -->
    <el-dialog :title="title" :visible.sync="open" width="55%" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules" label-width="80px">
        <el-form-item label="师训号" prop="teacherNumber">
          <el-input v-model="form1.teacherNumber" placeholder="请输入师训号" />
        </el-form-item>
        <el-form-item label="学校" prop="teacherUnit">
          <el-input v-model="form1.teacherUnit" placeholder="请输入学校" />
        </el-form-item>
        <el-form-item label="姓名" prop="teacherName">
          <el-input v-model="form1.teacherName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="工作职务" prop="teacherPosition">
          <el-input v-model="form1.teacherPosition" placeholder="请输入工作职务" />
        </el-form-item>
        <el-form-item label="手机号" prop="teacherPhone">
          <el-input v-model="form1.teacherPhone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 二维码下载 -->
    <el-dialog title="查看" :visible.sync="open1" width="55%" append-to-body>
      <div class="dialog_content">
        <canvas id="myCanvas"></canvas>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadQrCode">下载</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="40%" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        action=""
        :before-upload="handleBeforeUpload"
      >
        <el-button type="primary">上传文件</el-button>
      </el-upload>
      <div v-if="studentExcel.name" class="excel_item">{{studentExcel.name}}</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :disabled="!studentExcel.name">确 定</el-button>
        <el-button @click="cancelExcel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import QRCode from 'qrcode'
import {
  addTraining, addTrainingTeacher,
  delTraining,
  delTrainingCourse, delTrainingTeacher, editTrainingTeacher,
  getTrainingInfo, importStudent,
  listTrainingCourse,
  listTrainingTeacherList, updateTraining
} from "@/api/classai/training";

export default {
  name: "TrainingDetail",
  dicts: ['classai_common_status', 'teacher_sex', 'teacher_title','px_type','training_format','px_score_type'],
  data() {
    return {
      detail: {},
      type:1,
      activeName: 'first',
      trainingCourseList:[],
      trainingStudentList:[],
      open:false,
      open1:false,
      loading:false,
      qrCodeDataUrl: '',
      QrCodeTitle: '',
      title:'',
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
      },
      rules: {
        teacherName: [
          { required: true, trigger: "blur", message: "请输入教师名称" }
        ],
        teacherPhone: [
          { required: true, trigger: "blur", message: "请输入联系方式" }
        ],
        teacherUnit: [
          { required: true, trigger: "blur", message: "请输入学校名称" }
        ],
        teacherNumber: [
          { required: true, trigger: "blur", message: "请输入师训号" }
        ],
      },
      form:{},
      form1:{},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      courseQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      courseTotal: 0,
      studentExcel: {}
    };
  },
  created() {
    this.getList()
    this.getCourseList()
    this.getStudentList()
    if (this.$route.query.from === '1') {
      this.activeName = 'second'
    }
  },
  methods: {
    handleBeforeUpload(e) {
      this.studentExcel = e
      return false
    },
    cancelExcel() {
      this.upload.open = false
      this.studentExcel = {}
    },
    submitFileForm() {
      importStudent(this.studentExcel, this.$route.query.id).then(res => {
        if (res.code !== 200) return this.$message.warning("导入失败")
        this.$message.success("导入成功")
        this.upload.open = false;
        this.getStudentList()
      })
    },
    openImportStudent(){
      this.upload.title = "学生导入";
      this.upload.open = true;
    },
    toStudentSituation(id){
      this.$router.push(`/pxmanage/studentSituation?id=${id}`)
    },
    toCourseSituation(id){
      this.$router.push(`/pxmanage/courseSituation?id=${id}`)
    },
    getList(){
      let id = this.$route.query.id
      getTrainingInfo(id).then(response => {
        this.form = response.data;
        this.form.state = this.getStatus(this.form.startTime,this.form.endTime)
      });
    },
    getCourseList(){
      let id = this.$route.query.id
      listTrainingCourse({trainingId:id, ...this.courseQueryParams}).then(response => {
        this.trainingCourseList = response.rows;
        this.courseTotal = response.total
      });
    },
    getStudentList(){
      let id = this.$route.query.id
      listTrainingTeacherList({trainingId:id, ...this.queryParams}).then(response => {
        this.trainingStudentList = response.rows;
        this.total = response.total;
      });
    },
    getStatus(startTime, endTime) {
      const now = new Date().getTime(); // 当前时间戳
      const start = new Date(startTime).getTime();
      const end = new Date(endTime).getTime();

      if (now < start) {
        return '未开始';
      } else if (now >= start && now <= end) {
        return '进行中';
      } else {
        return '已结束';
      }
    },
    /** 新增课程 */
    handleAdd() {
      this.$router.push(`/pxmanage/addCourse?id=${this.form.id}`)
      this.$router.push({ path: '/pxmanage/addCourse', query: { id: this.form.id,ids:this.$route.query.id } });
    },
    handleUpdate(e){
      this.$router.push({ path: '/pxmanage/editCourse', query: { id: e.id, traingId: this.form.id,ids:this.$route.query.id } });
      // this.$router.push(`/pxmanage/editCourse?id=${e.id}`)
    },
    handleAddStudent(){
      this.title='新增学员'
      this.form1.trainingId = this.$route.query.id
      this.open = true
    },

    /** 删除学员按钮操作 */
    handleDeleteStudent(row) {
      const ids = row.id
      this.$modal.confirm('是否确认删除培训信息编号为"' + ids + '"的数据项？').then(function() {
        return delTrainingTeacher({teacherId:ids,trainingId:this.$route.query.id});
      }).then(() => {
        this.getStudentList()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleEdit(row){
      this.title='修改学员'
      this.form1 = row
      this.form1.trainingId = this.$route.query.id
      this.open = true
    },
    submitForm(){
      this.$refs["form1"].validate(valid => {
        if (valid) {
          if (this.form1.id != null) {
            editTrainingTeacher(this.form1).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getStudentList()
            });
          } else {
            addTrainingTeacher(this.form1).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getStudentList()
            });
          }
        }
      });
    },
    /** 删除课程按钮操作 */
    handleDelete(row) {
      const ids = row.id
      this.$modal.confirm('是否确认删除培训信息编号为"' + ids + '"的数据项？').then(function() {
        return delTrainingCourse(ids);
      }).then(() => {
        this.getCourseList()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleOpenCode(row){
      QRCode.toDataURL(row.id, {
          width: 550, // 设置宽高，单位像素
        })
        .then(url => {
          this.open1 = true
          this.QrCodeTitle = row.trainingTheme
          this.qrCodeDataUrl = url
          this.drawBase64WithText(url, row.trainingTheme)
        })
        .catch(err => {
          console.error(err)
        })
    },
    drawBase64WithText(base64, text) {
      const img = new Image();
      img.crossOrigin = "anonymous";
      img.src = base64;

      img.onload = () => {
        const padding = 10;
        let textHeight = 20; // 多行预留高度
        const fontSize = 25;
        const bottomPadding = 40;
        const lineHeight = fontSize * 1.5;

        const width = img.width;
        const height = img.height + textHeight + padding + bottomPadding;

        const canvas = document.getElementById("myCanvas");
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext("2d");

        // 白色背景
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, width, height);

        // 绘制图片
        ctx.drawImage(img, 0, 0, width, img.height);

        // 绘制可换行文字
        ctx.fillStyle = "#000000";
        ctx.font = `${fontSize}px sans-serif`;
        ctx.textAlign = "center";
        ctx.textBaseline = "top"; // 使用 top，方便换行递增 Y 坐标

        const maxTextWidth = width * 0.9; // 预留左右 padding
        const x = width / 2;
        const y = img.height - 30;

        this.wrapText(ctx, text, x, y, maxTextWidth, lineHeight);

      };
    },
    wrapText(ctx, text, x, y, maxWidth, lineHeight) {
      const words = text.split('');
      let line = '';
      let testLine = '';
      let testWidth = 0;

      for (let n = 0; n < words.length; n++) {
        testLine = line + words[n];
        testWidth = ctx.measureText(testLine).width;
        if (testWidth > maxWidth && n > 0) {
          ctx.fillText(line, x, y);
          line = words[n];
          y += lineHeight;
        } else {
          line = testLine;
        }
      }
      ctx.fillText(line, x, y);
    },
    downloadQrCode() {
      const canvas = document.getElementById('myCanvas');
      const dataURL = canvas.toDataURL('image/png');

      const a = document.createElement('a');
      a.href = dataURL;
      a.download = this.QrCodeTitle;
      document.body.appendChild(a); // Safari 兼容
      a.click();
      document.body.removeChild(a);
    },
    cancel(){
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form1 = {
        teacherNumber: null,
        teacherUnit: null,
        teacherName: null,
        teacherPosition: null,
        teacherPhone: null,
      };
      this.resetForm("form1");
    },
  }
};
</script>
<style lang="scss" scoped>
.training_detail_root{
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #F3F4F6;
  .training_detail_root_top{
    width: 100%;
    padding: 24px;
    box-sizing: border-box;
    border-radius: 8px;
    background: #FFFFFF;
    box-shadow: 0px 1px 2px -1px rgba(0, 0, 0, 0.1),0px 1px 3px 0px rgba(0, 0, 0, 0.1);
    position: relative;
    .situation_button{
      position: absolute;
      right: 24px;
      top: 24px;
    }
    .training_detail_root_top_title{
      font-size: 18px;
      font-weight: 500;
      line-height: 28px;
      color: #111827;
      margin-bottom: 24px;
    }
    .training_detail_root_top_row{
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .training_detail_root_top_row_li{
        flex: 1;
        margin-bottom: 16px;
        .li_title{
          font-size: 14px;
          font-weight: 500;
          line-height: 20px;
          color: #6B7280;
          margin-bottom: 5px;
        }
        .li_title_content{
          font-size: 14px;
          line-height: 20px;
          color: #111827;
        }
      }
    }
  }
  .training_detail_root_bottom{
    flex: 1;
    justify-content: space-between;
    align-items: center;
    margin-top: 24px;
    .bottom_content{
      padding: 24px;
      box-sizing: border-box;
      border-radius: 8px;
      background: #ffffff;
      box-shadow: 0px 1px 2px -1px rgba(0, 0, 0, 0.1),0px 1px 3px 0px rgba(0, 0, 0, 0.1);
      .bottom_content_title{
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-bottom: 24px;
        .bottom_content_title_left{
          font-size: 18px;
          font-weight: 500;
          line-height: 28px;
          color: #111827;
        }
      }
    }
  }
}
.excel_item {
  border-radius: 10px;
  border: 1px solid #dedede;
  padding: 8px 10px;
  margin-top: 10px;
}
.button-status{
  font-size: 12px;
  padding: 4px 8px;
  box-sizing: border-box;
  border-radius: 15px;
}
.status0{
  color: rgb(245, 108, 108);
  background: rgb(254, 240, 240);
}
.status1{
  color: #854D0E;
  background: #FEF9C3;
}
.status2{
  color: rgb(144, 147, 153);
  background: rgb(244, 244, 245);
}
.status3{
  color: #166534;
  background: #DCFCE7;
}
.status4{
  color: #1E40AF;
  background: #DBEAFE;
}
.dialog_content {
  display: flex;
  align-items: center;
  canvas {
    width: 500px;
    aspect-ratio: 1 / 1.1;
    margin: 20px auto;
  }
}
</style>
